package com.meow.action.admin.generater;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.List;

import javax.imageio.stream.FileImageInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.meow.dao.entity.visa.Continent;
import com.meow.dao.entity.visa.VisaCountry;
import com.meow.dao.mapper.visa.ContinentDao;
import com.meow.dao.mapper.visa.VisaCountryDao;
import com.meow.util.AjaxOut;

@Controller
@RequestMapping("/admin/visa/GeneratFrontAction/")
public class GeneratFrontAction {

	private Logger logger = Logger.getLogger(GeneratFrontAction.class);
	
	@Autowired
	private ContinentDao continentDao;
	
	@Autowired
	private VisaCountryDao visaCountryDao;
	
	@RequestMapping("generatFront.action")
	public void generatFront(HttpServletRequest request, HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		obj.put("success",true);
		try {
			generateIndex(request);
			generateCounties(request);
			
			obj.put("result","success");
		}
		catch (Exception e) {
			logger.error("", e);
			obj.put("result","error");
			obj.put("info",e.getMessage());
		}
		AjaxOut.responseText(response, obj.toString());
	}
	
	/**
	 * 生成首页
	 * @param allContinentData
	 */
	private void generateIndex(HttpServletRequest request) throws Exception {
		File desFile = new File("C:\\MeowcashVisa");
		if(!desFile.isDirectory() || !desFile.exists()) {
			desFile.mkdirs();
		}
		
		StringBuffer countierTabBuf = new StringBuffer();
		List allContinentData = continentDao.selectByEntity(null);
		for(int i = 0; i < allContinentData.size(); i++) {
			Continent ety = (Continent) allContinentData.get(i);
			
			countierTabBuf.append("\n<tr><td colspan=\"8\" class=\"contentTD\">"  + ety.getName() + "</td></tr>");
			
			VisaCountry cEty = new VisaCountry();
			cEty.setContinentId(ety.getId());
			List countryListData = visaCountryDao.selectByEntity(cEty);
			
			if(countryListData.size() == 0)
				continue;
			
			countierTabBuf.append("\n<tr>");
			
			int columnIndex = 0;
			for(int j = 0; j < countryListData.size(); j++) {
				if(columnIndex > 7) {
					countierTabBuf.append("\n</tr>\n<tr>");
					columnIndex = 0;
				}
				
				VisaCountry country = (VisaCountry) countryListData.get(j);
				countierTabBuf.append("\n<td class=\"countryTD\"><a target=\"_blank\" href=\"country\\country_" + country.getId() + ".html\" class=\"countryA\">");
				countierTabBuf.append(country.getNameCn());
				countierTabBuf.append("\n</a></td>");
				columnIndex ++;
			}
			
			if(columnIndex > 0 && columnIndex <= 7) {
				countierTabBuf.append("\n</tr>");
			}
		}
		
		String realPath = request.getSession().getServletContext().getRealPath("/");
		BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(realPath + "/template/index.tl"), "gbk"));
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:\\MeowcashVisa\\index.html"),"gbk"));
		
		String line = null;
		while((line = reader.readLine()) != null) {
			if(line.trim().equalsIgnoreCase("${DataTable_Country}")) {
				writer.write(countierTabBuf.toString() + "\n");
			}
			else {
				writer.write(line + "\n");
			}
		}
		reader.close();
		writer.close();
	}
	
	/**
	 * 生成各国家详细页面
	 * @param allContinentData
	 */
	private void generateCounties(HttpServletRequest request) throws Exception {
		List<VisaCountry> countryListData = visaCountryDao.selectAllInfo();
		for(int j = 0; j < countryListData.size(); j++) {
			VisaCountry country = (VisaCountry) countryListData.get(j);
			
			String realPath = request.getSession().getServletContext().getRealPath("/");
			BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(realPath + "/template/country/country_detail.tl"), "gbk"));
			
			String fp = "C:\\MeowcashVisa\\country\\country_" + country.getId() + ".html";
			File f = new File(fp);
			if(!f.exists()) {
				f.getParentFile().mkdirs();
			}
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fp),"gbk"));
			
			String line = null;
			while((line = reader.readLine()) != null) {
				if(line.trim().equalsIgnoreCase("${country_detail}")) {
					writer.write(country.getContent() + "\n");
				}
				else {
					writer.write(line + "\n");
				}
			}
			reader.close();
			writer.close();
		}
		
	}
}
